﻿using Microsoft.Phone.Controls;
using NaverOpenApiLibrary.Services;
using NaverOpenApiLibrary.Models;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Controls;
using System.Diagnostics;
using Microsoft.Phone.Tasks;
using System;


namespace NaverOpenApiRTSample
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        // Constructor
        public MainPage()
        {
            InitializeComponent();
        }

        private void PhoneApplicationPage_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            System.Threading.Thread th = new System.Threading.Thread(doThreading);
            th.Start();
        }

        // ****************************************************
        // REPLACE BELOW WITH YOUR API KEY
        // API Keys can be issued at: http://dev.naver.com/openapi/
        private const string SHORT_URL_API_KEY = "f9b1b8aed4bbe2949992ca72023dfed7";
        private const string SEARCH_API_KEY = "4f60b03829def6e96147d436882f10ec";

        private void doThreading()
        {
            // URL 단축 서비스 예제
            UrlShortnerService urlService = new UrlShortnerService(SHORT_URL_API_KEY);
            urlService.ApiServiceCompleted += (s, u) =>
            {
                if (u.ResultCode != null)
                    System.Diagnostics.Debug.WriteLine(u.Urls.ShortUrl);
                else
                    System.Diagnostics.Debug.WriteLine("[MainPage] Invalid API request or API key");
            };
            urlService.DoShorten("http://dev.naver.com/");

            // 실급검 예제
            HotTopicsService hotTopicService = new HotTopicsService(SEARCH_API_KEY);
            hotTopicService.ApiServiceCompleted += (s, h) =>
            {
                if (h != null)
                    for (int i = 0; i < 10; i++)
                        System.Diagnostics.Debug.WriteLine(h.HotTopics[i].Keyword);
                else
                    System.Diagnostics.Debug.WriteLine("[MainPage] Invalid API request or API key");
            };
            hotTopicService.GetHotTopics();

            // 뉴스 검색 예제
            NewsSearchService newsSearcher = new NewsSearchService(SEARCH_API_KEY);
            newsSearcher.ApiServiceCompleted += (s, n) =>
            {
                if (n != null)
                    //for (int i = 0; i < 20; i++)
                    //    System.Diagnostics.Debug.WriteLine(n.Channel.Item[i].Title);
                    foreach (NewsDetail news in n.Channel.Item)
                        System.Diagnostics.Debug.WriteLine(news.Title);
                else
                    System.Diagnostics.Debug.WriteLine("[MainPage] Invalid API request or API key");
            };
            newsSearcher.GetNews("대선", 1, 20);

            // 지식인 예제
            KinService kinSearcher = new KinService(SEARCH_API_KEY);
            kinSearcher.ApiServiceCompleted += (s, k) =>
                {
                    if (k != null)
                        foreach (KinItem kin in k.Channel.Items)
                            System.Diagnostics.Debug.WriteLine(kin.Title);
                    else
                        System.Diagnostics.Debug.WriteLine("[MainPage] Invalid API request or API key");
                    
                };
            kinSearcher.GetKin("롯데월드", 1, 20, KinService.Sort.Count);

            // 블로그 예제 + 화면 출력
            BlogService blogSearcher = new BlogService(SEARCH_API_KEY);
            blogSearcher.ApiServiceCompleted += (s, b) =>
                {
                    if (b != null)
                    {
                        foreach (BlogItem blog in b.Channel.Items)
                            System.Diagnostics.Debug.WriteLine(blog.Title);

                        List<BlogItem> blogItems = new List<BlogItem>(b.Channel.Items);

                        blogItems.ForEach(item => { item.Title = Regex.Replace(item.Title, "<.*?>", string.Empty); });

                        Dispatcher.BeginInvoke(() =>
                            {
                                SearchResultListBox.ItemsSource = blogItems;
                            });
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("[MainPage] Invalid API request or API key");
                    }
                };
            blogSearcher.GetBlog("에버랜드");

        }

        private void SearchResultListBox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            ListBox senderListBox = (ListBox)sender;
            BlogItem item = (BlogItem)senderListBox.SelectedItem;

            WebBrowserTask wbt = new WebBrowserTask();
            wbt.Uri = new Uri(item.Link);
            wbt.Show();

            Debug.WriteLine("");
        }

        
    }
}